package de.koller.gravity.mech.universe;

import de.koller.gravity.mech.particle.Particle;
import de.koller.gravity.mech.particle.ParticleEngine;
import de.koller.gravity.mech.particle.environment.IParticleEnvironment;
import de.koller.oceanFramework.math.RVec3d;

public class MoltPlanet implements IParticleEnvironment {

	public static final double MOLT_RANGE_SQUARED = 1*1;
	
	@Override
	public void stepParticle( Particle p, ParticleEngine engine ) {
		if( p instanceof PlanetaryMass == false )
			return;
		
		for( Particle o : engine.particles ) {
			if( o == p )
				continue;
			if( o instanceof PlanetaryMass == false )
				continue;
			
			
			
			double le = RVec3d.difference( p.position, o.position ).getLengthSquared();
			if( le > MoltPlanet.MOLT_RANGE_SQUARED + o.size*.5 + p.size*.5 )
				continue;
			
			PlanetaryMass p1 = (PlanetaryMass)p;
			PlanetaryMass p2 = (PlanetaryMass)o;
			
			if( p1.invalid || p2.invalid )
				continue;
			
			double e1 = .5f * p1.getMass() * p1.velocity.getLengthSquared();
			double e2 = .5f * p2.getMass() * p2.velocity.getLengthSquared();
			
			RVec3d e = new RVec3d();
			e.add( p1.velocity.newInstace().normalize().mult( e1 ) );
			e.add( p2.velocity.newInstace().normalize().mult( e2 ) );
			double ne = Math.sqrt( e.getLength() / (.5 * (p1.getMass()+p2.getMass()) ) );
			
			e.normalize().mult( ne );
			
			engine.particles.remove( o );
			engine.particles.remove( p );
			
			
			PlanetaryMass n = new PlanetaryMass( p1.getMass() + p2.getMass() );
			n.velocity.set( e );
			n.position.set( p1.position.add( p2.position ).div( 2 ) );
			engine.particles.add( n );
			
			p1.invalid = true;
			p2.invalid = true;
			
		}	
	}
	
}
